import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { queryFakeList, remove } from './service';
const R = require('ramda');
import { BasicListItemDataType } from './data.d';

export interface StateType {
  list: BasicListItemDataType[];
  pagination: any;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    appendFetch: Effect;
    submit: Effect;
  };
  reducers: {
    queryList: Reducer<StateType>;
    appendList: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'manageMessage',

  state: {
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    }
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryFakeList, payload);

      const { page, size, totalRow } = response.content.page;
      yield put({
        type: 'queryList',
        payload: {
          list: Array.isArray(response.content.list) ? response.content.list : [],
          pagination: { current: page, pageSize: size, total: totalRow }
        },
      });
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(remove, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (payload.onSuccess) payload.onSuccess();
    },
  },

  reducers: {
    queryList(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    appendList(state = { list: [] }, action) {
      return {
        ...state,
        list: state.list.concat(action.payload),
      };
    },
  },
};

export default Model;
